#define _CRT_SECURE_NO_WARNINGS
#include"game.h"

extern char mine[HS][LS];
extern char show[HS][LS];
extern int minecount;
void Menu()
{
	printf("********************************\n");
	printf("********     1.Play     ********\n");
	printf("********     0.Exit     ********\n");
	printf("********************************\n");
}

void Initialize(char board[HS][LS], char a, int h, int l)
{
	int i = 0, j = 0;
	for (i = 0; i < h; i++)
	{
		for (j = 0; j < l; j++)
		{
			board[i][j] = a;
		}
	}
}

void Show(char board[HS][LS])
{
	printf("----------MineSweeper----------\n");
	int i = 1, j = 1;
	printf("0 1 2 3 4 5 6 7 8 9\n");
	for (i = 1; i <= H && i > 0; i++)
	{
		printf("%d ", i);
		for (j = 1; j <= L && j > 0; j++)
		{
			printf("%c ", board[i][j]);
		}
		printf("\n");
	}
	printf("-------------------------------\n");
}

Mine(char mine[HS][LS])
{
	int a = 1, b = 1;
	int count = 0;
	while (count < minecount)
	{
		a = (rand() % 9 + 1);
		b = (rand() % 9 + 1);
		if (mine[a][b] == ' ')
		{
			mine[a][b] = '!';
			count++;
		}
	}
}

int Judge(int x, int y)
{
	static int judge = 0;
	int count = mine[x - 1][y - 1] +
		mine[x - 1][y] +
		mine[x - 1][y + 1] +
		mine[x][y - 1] +
		mine[x][y + 1] +
		mine[x + 1][y - 1] +
		mine[x + 1][y] +
		mine[x + 1][y + 1] -
		(8 * ' ');


	switch (mine[x][y])
	{
	case ' ':
	{
		show[x][y] = count + 48;
		judge++;
		if ((H * L - minecount )== judge)
		{
			Show(show);
			return 2;
		}
		return 1;
	}
	case '!':
	{
		return 0;
	}
	}
		
}

void Game()
{
	Initialize(mine, ' ', HS, LS);
	Initialize(show, '*', HS, LS);
	do
	{
		printf("Enter mine counts.\n");
		scanf("%d", &minecount);
		if (minecount >= H * L || minecount <= 0)
		{
			printf("Typing error.\n");
		}
	}while (minecount >= H * L || minecount <= 0);
	Mine(mine);
	while (1)
	{

		int x = 0, y = 0;
		int ret = 0;
		do
		{
		again:
			Show(show);
			//Show(mine);
			printf("Enter the coordinates.\n");
			scanf("%d %d", &x, &y);
			if (x < 1 || x > 9 || y < 1 || y > 9)
			{
				printf("Typing error.\n");
			}
			else if (show[x][y] != '*')
			{
				printf("That slot is occupied.\n");
				goto again;
			}
			ret = Judge(x, y);
		} while (1 == ret);
		if (0 == ret)
		{
			printf("You have lost.\n");
			Show(mine);
			break;
		}
		else if (2 == ret)
		{
			printf("You win.\n");
			Show(mine);
			break;
		}
	}
}